from fastapi import FastAPI, UploadFile, File
from fastapi.responses import JSONResponse
from fastapi.staticfiles import StaticFiles
import uvicorn
import os

app = FastAPI()

# 静态文件目录
UPLOAD_FOLDER = "/Users/duyi/PycharmProjects/interview_voice_project/__000__demo/上传语音代码/uploads"
os.makedirs(UPLOAD_FOLDER, exist_ok=True)

# 挂载静态目录，访问路径 /static/xxx.png
app.mount("/static", StaticFiles(directory=UPLOAD_FOLDER), name="static")


@app.post("/upload/")
async def upload_file(file: UploadFile = File(...)):
    file_path = os.path.join(UPLOAD_FOLDER, file.filename)
    with open(file_path, "wb") as f:
        f.write(await file.read())

    # 返回可访问的URL（这里用http://127.0.0.1:8000，部署后改成你的域名 + https）
    file_url = f"http://127.0.0.1:8000/static/{file.filename}"
    return JSONResponse({"filename": file.filename, "url": file_url})


if __name__ == "__main__":
    uvicorn.run(app, host="0.0.0.0", port=8000)
